package com.tianjian.common.online;

import java.util.Vector;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tianjian.oa.system.pojos.UserInfo;

public class OnLineUsers implements HttpSessionBindingListener {

	private Logger logger = Logger.getLogger(OnLineUsers.class);

	private static Vector<UserInfo> USERS = new Vector<UserInfo>();

	private UserInfo user;

	public OnLineUsers(UserInfo user) {
		this.user = user;
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent)
	 */
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		if (user != null) {
			USERS.add(user);
			USERS.trimToSize();
		}
		logger.info("[" + user.getId() + ":" + user.getUsername() + ":" + user.getName() + "] - 登陆系统, 当前在线人数:" + USERS.size() + "人.");
		update(event);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent)
	 */
	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		USERS.remove(user);
		logger.info("[" + user.getId() + ":" + user.getUsername() + ":" + user.getName() + "] - 退出系统, 当前在线人数:" + USERS.size() + "人.");
		update(event);
	}

	private void update(HttpSessionBindingEvent event) {
		try {
			WebApplicationContextUtils.getRequiredWebApplicationContext(event.getSession().getServletContext()).getBean(OnLineMapper.class).updateOnline(USERS);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
